var mapid = "";
var deviceid ="";
var hidId,imgNum;
//初始化楼栋
$(function(){
    $(document).off("click",".left-menu dt");
    getMenuList();
});
//获取楼层菜单
function getMenuList(){
    // PostForm("/cwp/front/sh/intebuilding!execute", "uid=intelligentbuilding001_3", "", outputMenuList, '',"");
    $.getJSON('/cwp/src/json/device/intebuilding_ill_001_3.json',function(data){
        outputMenuList(data);
    })
}
//输出楼层菜单
function outputMenuList(result){
    if(result.returnCode == 0){
        if(result.beans.buildingDesc!="B1"){
            template.helper('numFormat', function(inp) {
                if(inp == 2){
                    return "cur";
                }
            });
            var outHtml = template("menuListTmpl", result);
            $("#floorMenuList").html(outHtml);

            template.helper('mapFormat', function(inp) {
                if(inp == 2){
                    return "cur animated fadeInUp";
                }
            });
            template.helper('mapImgFormat', function(inp) {
                    return "../../../assets/img/building/floor-1.png";
            });
            var outHtml = template("mapTmpl", result);
            $("#floor-list").html(outHtml);
            getDevice(result.beans[1].buildingId);
        }


    }else{
        tipModal("icon-cross", "获取楼层失败");
    }
}
//获取所有子设备
function getDevice(floorId){
    mapid = floorId;
    // PostForm("/cwp/front/sh/device!execute", "uid=d001_4&pageSize=100&currentPage=1&deviceTypeId=1005&isDeviceControl=0&buildingId="+floorId, "", outputDevice, '');

    $.getJSON('/cwp/src/json/device/device_ill_d001_4.json',function(data){
        outputDevice(data)
    })
}
//输出有所子设备
function outputDevice(result){
    if(result.returnCode  == 0){
        // result.beans.sort(sotrObjCode("devicePositionCode"));
        var outHtml = template("deviceTmpl", result);
        $("#deviceList").html(outHtml);
        var lightImg = "";
        var ligntAear="";
        var sceneLevel = "";
        var regio = ""
        var deviceY = "";
        var deviceX = "";
        var calssB = "";
        var regioD = "";
        for(var i=0;i<result.beans.length;i++){
            if(result.beans[i].devicePositionCode!=""){
                // sceneLevel=result.beans[i].devicePositionCode.split('/')[1];
                // regio=result.beans[i].devicePositionCode.split('/')[0];
                // regioD=parseInt(result.beans[i].devicePositionCode.split('/')[2])%4;
                sceneLevel = 1;
                regio = 4;
                regioD = 0;
                //三级场景级二级场景调整
                if(sceneLevel == 3){
                    deviceX =(parseInt(result.beans[i].deviceX) + 46);
                    deviceY =(parseInt(result.beans[i].deviceY) + 1);
                }
                else{
                    deviceX =(parseInt(result.beans[i].deviceX) + 9);
                    deviceY =(parseInt(result.beans[i].deviceY) + 9);
                }
                //D区照明样式调整
                if(regio == 4 & sceneLevel == 3 ){
                    deviceY =(parseInt(result.beans[i].deviceY) + 3);
                    deviceX =(parseInt(result.beans[i].deviceX) + 9);
                }
                //B区整区宽度样式调整
                if(regio == 1 & sceneLevel == 3){
                    calssB = "regioB";
                }else{
                    calssB = "";
                }
                //A-D、C-D区域样式
                if(regioD == 0 && sceneLevel != 3){
                    regio = 4;
                    deviceY =(parseInt(result.beans[i].deviceY) + 18);
                }
            }
            lightImg += "<img class='img-l ' data-id="+result.beans[i].deviceId +" title='"+result.beans[i].devicePositionDescribe+"' style='left:"+ deviceX +"%;top:"+ deviceY +"%;' data-img='off' data-toggle='tooltip' data-placement='bottom' src='../../../assets/img/building/devices/light_off1.png' alt=''/>";
            ligntAear+="<a class='"+ calssB +"  regio"+ regio +" area area"+sceneLevel+"' data-id="+result.beans[i].deviceId +" data-groupAddr="+result.beans[i].devicePositionCode +" style='left:"+result.beans[i].deviceX+"%;top:"+ result.beans[i].deviceY +"%'></a>";
        }
        $(".device-coordinate-item").html("");
        $("#bf2cac1e-d440-4e22-a0e4-a32c3ac34036").html(lightImg+ligntAear);
        //显示地址提示
        setTimeout(function() {
            $(".img-l").tooltip({trigger : 'manual'} );
            $(".img-l").tooltip('show');
        }, 100);
        //IE8 重复刷新
        if(lessThenIE8){
            setTimeout(function() {
                $(".img-l").tooltip({trigger : 'manual'} );
                $(".img-l").tooltip('show');
            }, 10);
        }


        //搜索框 搜索设备
        var deviceAddr = $("#btn-search-device").val();
        if(deviceAddr != ""){
            searchDevice(deviceAddr);
        }

    }else{
        tipModal("icon-cross", "获取设备失败");
    }

}

//IE 8
var lessThenIE8 = function () {
    var UA = navigator.userAgent,
        isIE = UA.indexOf('MSIE') > -1,
        v = isIE ? /\d+/.exec(UA.split(';')[1]) : 'no ie';
    return v == 8;
}();



//楼层切换
$(document).on("click",".floor-item",function(){
    var floorId = $(this).attr("data-id");
    $(".floor-item").removeClass("cur");
    $(this).addClass("cur");
    $(".info-box").hide();
    $(".info-box").removeClass("show");
    $("#hidDeviceID").val("");
    //显示对应楼层
    getDevice(floorId);
    $("#floor-list .floor-image").removeClass("cur animated fadeInUp");
    $("#floor"+floorId).addClass("cur animated fadeInUp");
    $("#device-list").addClass("animated fadeInRight");
    $("#deviceInfo").find("li").remove();
    $(".t-building").removeClass("t-building-open");
    setTimeout(function() {
        $("#device-list").removeClass("animated fadeInRight");
    }, 1000);

});




//开关
$(document).on("click",".t-btn-open",function(){
    $("#hidSwitch").val(1);
    var deviceAds=$(".device-item.cur").html();
    //显示提示内容
    $("#modalSwitch .content").html("是否打开?<br/>"+deviceAds+"设备");
    $("#modalSwitch").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());


});
$(document).on("click",".t-btn-close",function(){
    $("#hidSwitch").val(0);
    var deviceAds=$(".device-item.cur").html();
    //显示提示内容
    $("#modalSwitch .content").html("是否关闭?<br/>"+deviceAds+"设备");
    $("#modalSwitch").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
});

//确认执行开关
$("#btnConfirm").on("click",function(){
    var sv = $("#hidSwitch").val();
    var groupAddr = $(".area.cur").attr("data-groupAddr");
    $("#modalSwitch").modal("hide");
    //开灯
    if(sv == 1){
        controlSwitch(groupAddr,"on");
    }
    else{
        controlSwitch(groupAddr,"off");
    }

});

//左侧菜单悬浮
$(document).on("mouseover","#deviceList li",function(){
    imgNum=$(this).index();
    $(".area").eq(imgNum).addClass("hover");
}).on("mouseout",function(){
    $(".area").removeClass("hover");
});

var that="";
$(document).on("mouseover",".img-l",function(){
    var data_id=$(this).attr("data-id");
    $(".area[data-id="+data_id+"]").addClass("hover");
    that=$(this);
    if(!that.hasClass("cur")) {
        that.attr("src", "../../../assets/img/building/devices/light_off.png");
    }
}).on("mouseout",".img-l",function(){
    if(!that.hasClass("cur")){
        that.attr("src","../../../assets/img/building/devices/light_off1.png");
    }
});


//B区照明
$(document).on("click",".img-l",function(){
    var onimg = "../../../assets/img/building/devices/light_on.png";
    $(this).addClass("cur");
    //照明灯样式
    //循环赋予开灯的样式
    $(".device-coordinate-item.selected .img-l").attr("src","../../../assets/img/building/devices/light_off1.png");
    if($(this)[0].attributes[6].value != onimg){
        $(this).attr("src","../../../assets/img/building/devices/light_off.png");
    }
    $(".img-l").each(function(){
        if($(this).attr("data-img") == "on"){
            $(this).attr("src","../../../assets/img/building/devices/light_on.png");
        }
    })
    //照片区域显示
    $(".area").removeClass("cur");
    $(".area.hover").addClass("cur");
    //显示详情
    var title = $(this).attr("data-original-title");

    //选中菜单
    var deviceId=$(this).attr("data-id");
    hidId = deviceId;
    showDetail(deviceId);
    $(".device-item").removeClass("cur");
    $(".device-item[data-id="+deviceId+"]").addClass("cur");
});

//B区照明
$(document).on("click",".areaB",function(){
    $(".areaB").removeClass("cur");
    $(this).addClass("cur");
});


//设备列表单击事件
$(document).on("click",".device-item",function(){
    $(".device-item").removeClass("cur");
    $(this).addClass("cur");
    $(".area").removeClass("cur");
    $(".area.hover").addClass("cur");
    $(".img-l").eq(imgNum).addClass("cur");
    var title = $(this).text();
    $("#deviceInfo .title").html(title);
    var deviceId = $(this).attr("data-id");
    hidId = deviceId;
    //循环赋予开灯的样式
    $(".device-coordinate-item.selected .img-l").attr("src","../../../assets/img/building/devices/light_off1.png");
    $(".img-l.cur").each(function(){
        if($(this).attr("data-img") == "on"){
            $(this).attr("src","../../../assets/img/building/devices/light_on.png");
        }else{
            if($(this).attr("data-id") == hidId){
                $(this).attr("src","../../../assets/img/building/devices/light_off.png");
            }
        }

    })
    showDetail(deviceId);
});

//单击照亮设备
$(document).on("click",".icon-lightbulb",function(){
    $(".area").removeClass("cur open");
    $(this).parent().addClass("cur");
    var deviceId = $(this).attr("data-id");
    showDetail(deviceId);
});

//开关

//显示详情
//获取设备信息
function showDetail(deviceId){
    $(".img-title").removeClass("hide");
    // PostForm("/cwp/front/sh/intebuilding!execute", "uid=i003_3&deviceId="+deviceId, "", outputDeviceInfo, '',"");
    $.get('',function(data){

    });
}

function outputDeviceInfo(result){
    if(result.returnCode == 0){
        var outHtml = template("deviceInfoTmpl", result);
        $("#deviceInfo").html(outHtml);
    }else{
        tipModal("icon-cross", "获取数据失败");
    }

}


//楼层容器自适应
$(window).resize(function(){
    autoWidth();
});


function autoWidth(){
    var w=$(".floor-image.cur img")[0].offsetWidth;
    $(".floor-image.cur").css("width",w+"px");
    setTimeout(function() {
        $(".img-l").tooltip({trigger : 'manual'} );
        $(".img-l").tooltip('show');
    },300);
}

//搜索
$("#btn-search-device").on("input",function(){
    var keyword=$(this).val();
    searchDevice(keyword);
});

//搜索框
function searchDevice(keyword){
    if(keyword == ""){
        $(".device-item").parent().show();
    }
    else{
        $(".device-item").each(function(){
            var text=$(this).text();
            if(text.indexOf(keyword) > -1){
                $(this).parent().show();
            }else{
                $(this).parent().hide();
            }

        });
    }
}

//可视化组件
$('#deviceList').slimScroll({
    width: 'auto', //可滚动区域宽度
    height: '500px', //可滚动区域高度
    size: '5px', //组件宽度
    alwaysVisible: true
});

//照明开关控制
function controlSwitch(groupAddr,sButton){
    var switchTxt = sButton=="on"?"打开":"关闭";
    $.ajax({
        timeout : 20000,
        type:"get",
        url: ipg_url+"/ipg/light/openLight",
        async:true,
        dataType: "text",
        data:{
            groupAddr:groupAddr,
            sButton:sButton
        },
        success:function (result) {
            if(result=="success"){
                tipModal("icon-checkmark", "照明设备"+switchTxt+"中");
                //开灯
                if(sButton == "on"){
                    $(".area.cur").addClass("open");
                    $(".img-l.cur").each(function(){
                        if($(this).attr("data-id") == hidId){
                            $(this).attr("src","../../../assets/img/building/devices/light_on.png");
                            $(this).attr("data-img","on");
                        }
                    })
                }
                else{
                    $(".area.cur").removeClass("open");
                    $(".img-l.cur").each(function(){
                        if($(this).attr("data-id") == hidId){
                            $(this).attr("src","../../../assets/img/building/devices/light_off1.png");
                            $(this).attr("data-img","off");
                        }
                    })

                }

            }
            else{
                tipModal("icon-cross", "照明设备"+switchTxt+"失败");
            }
            console.log(result);
        },
        error:function (result) {
            tipModal("icon-cross", "照明设备"+switchTxt+"失败");
            console.log(result);
        }
    });
}

//	排序场景
function sotrObjCode(propertyName){
    return function(object1,object2){
        var value1 = object1[propertyName].split("/");
        var value2 = object2[propertyName].split("/");
        var text1 = object1["room"].split("区");
        var text2 = object2["room"].split("区");
        if(value1[0] == value2[0]){
            if(value1[1] < value2[1]){
                return 1;
            }else if(value1[1] > value2[1]){
                return -1;
            }else{
                return 0;
            }
        }else if( text1[0] > text2[0]){
            return 1;
        }else if(text1[0] < text2[0]){
            return -1;
        }else{
            return 0;
        }
    }
}